import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Space,
  Button,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Tooltip,
  Typography,
  Row,
  Col,
  Statistic,
  Badge,
} from "antd";
import {
  MessageOutlined,
  LikeOutlined,
  EyeOutlined,
  UserOutlined,
  RobotOutlined,
  PushpinOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionFilter,
  DiscussionStats,
} from "../../common/types/discussion";
import { useUser } from "../../../contexts/UserContext";
import discussionService from "../../../services/discussion";
import aiService from "../../../services/ai";

const { Search } = Input;
const { Title, Text } = Typography;
const { confirm } = Modal;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const TeacherDiscussion: React.FC = () => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [discussions, setDiscussions] = useState<DiscussionPost[]>([]);
  const [stats, setStats] = useState<DiscussionStats>();
  const [filter, setFilter] = useState<DiscussionFilter>({
    sortBy: "latest",
  });
  const [selectedDiscussion, setSelectedDiscussion] = useState<string>();
  const [aiGenerating, setAiGenerating] = useState(false);

  useEffect(() => {
    loadDiscussions();
  }, [filter]);

  const loadDiscussions = async () => {
    setLoading(true);
    try {
      const { discussions: data } = await discussionService.getDiscussions(
        "all",
        filter
      );
      setDiscussions(data);

      const statsData = await discussionService.getStats("all");
      setStats(statsData);
    } catch (error) {
      message.error("加载讨论列表失败");
      console.error("加载讨论列表失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilter({ ...filter, keyword: value });
  };

  const handleSortChange = (value: "latest" | "popular" | "mostReplies") => {
    setFilter({ ...filter, sortBy: value });
  };

  const handleTagClick = (tag: string) => {
    setFilter({
      ...filter,
      tags: filter.tags?.includes(tag)
        ? filter.tags.filter((t) => t !== tag)
        : [...(filter.tags || []), tag],
    });
  };

  const handleDelete = (discussionId: string) => {
    confirm({
      title: "确认删除",
      icon: <ExclamationCircleOutlined />,
      content: "删除后将无法恢复，是否确认删除？",
      onOk: async () => {
        try {
          await discussionService.deleteDiscussion(discussionId);
          message.success("删除成功");
          loadDiscussions();
        } catch (error) {
          message.error("删除失败，请重试");
          console.error("删除讨论失败:", error);
        }
      },
    });
  };

  const handlePin = async (discussionId: string) => {
    try {
      await discussionService.pinDiscussion(discussionId);
      message.success("置顶状态已更新");
      loadDiscussions();
    } catch (error) {
      message.error("操作失败，请重试");
      console.error("置顶操作失败:", error);
    }
  };

  const handleAIReply = async (discussion: DiscussionPost) => {
    setAiGenerating(true);
    try {
      const response = await aiService.generateResponse(discussion);
      await discussionService.addAIReply(discussion.id, response);
      message.success("AI 回复已生成");
      loadDiscussions();
    } catch (error) {
      message.error("AI 回复生成失败，请重试");
      console.error("AI 回复生成失败:", error);
    } finally {
      setAiGenerating(false);
    }
  };

  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: (text: string, record: DiscussionPost) => (
        <Space>
          {record.isPinned && (
            <Tooltip title="已置顶">
              <PushpinOutlined style={{ color: "#1890ff" }} />
            </Tooltip>
          )}
          <a href={`/discussion/${record.id}`}>{text}</a>
          {record.aiResponse && (
            <Tag icon={<RobotOutlined />} color="purple">
              AI已回复
            </Tag>
          )}
        </Space>
      ),
    },
    {
      title: "作者",
      dataIndex: ["author", "name"],
      key: "author",
      render: (text: string, record: DiscussionPost) => (
        <Space>
          <UserOutlined />
          {text}
          <Tag color={record.author.role === "teacher" ? "blue" : undefined}>
            {record.author.role === "teacher" ? "教师" : "学生"}
          </Tag>
        </Space>
      ),
    },
    {
      title: "标签",
      dataIndex: "tags",
      key: "tags",
      render: (tags: string[]) => (
        <Space>
          {tags.map((tag) => (
            <Tag
              key={tag}
              color={filter.tags?.includes(tag) ? "blue" : undefined}
              style={{ cursor: "pointer" }}
              onClick={() => handleTagClick(tag)}
            >
              {tag}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: "统计",
      key: "stats",
      render: (_: any, record: DiscussionPost) => (
        <Space>
          <span>
            <EyeOutlined /> {record.views}
          </span>
          <span>
            <LikeOutlined /> {record.likes}
          </span>
          <span>
            <MessageOutlined /> {record.replies.length}
          </span>
        </Space>
      ),
    },
    {
      title: "发布时间",
      dataIndex: "createTime",
      key: "createTime",
      sorter: (a: DiscussionPost, b: DiscussionPost) =>
        new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: DiscussionPost) => (
        <Space>
          <Button
            type="link"
            icon={<PushpinOutlined />}
            onClick={() => handlePin(record.id)}
          >
            {record.isPinned ? "取消置顶" : "置顶"}
          </Button>
          <Button
            type="link"
            icon={<RobotOutlined />}
            loading={aiGenerating}
            onClick={() => handleAIReply(record)}
            disabled={!!record.aiResponse}
          >
            AI回复
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: "24px" }}>
      <Row gutter={24}>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="总讨论数"
              value={stats?.total || 0}
              prefix={<MessageOutlined />}
            />
          </StyledCard>
        </Col>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="今日新增"
              value={stats?.today || 0}
              prefix={<Badge status="processing" />}
            />
          </StyledCard>
        </Col>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="待回复"
              value={stats?.pending || 0}
              prefix={<Badge status="warning" />}
            />
          </StyledCard>
        </Col>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="AI回复率"
              value={stats?.aiReplyRate || 0}
              suffix="%"
              prefix={<RobotOutlined />}
            />
          </StyledCard>
        </Col>
      </Row>

      <StyledCard
        title={
          <Space>
            <Title level={4} style={{ margin: 0 }}>
              讨论列表
            </Title>
            <Tag color="blue">教师视图</Tag>
          </Space>
        }
        extra={
          <Space>
            <Search
              placeholder="搜索讨论..."
              onSearch={handleSearch}
              style={{ width: 300 }}
            />
            <Select
              value={filter.sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
              options={[
                { label: "最新", value: "latest" },
                { label: "最热", value: "popular" },
                { label: "最多回复", value: "mostReplies" },
              ]}
            />
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={discussions}
          loading={loading}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条讨论`,
          }}
        />
      </StyledCard>
    </div>
  );
};

export default TeacherDiscussion;
